package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"go-exp/pkg/errorx"
	"go-exp/zero/api/internal/svc"
	"go-exp/zero/api/internal/types"
	"go-exp/zero/rpc/oauth/pb/oauth"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	// todo: add your logic here and delete this line
	authResp, err := l.svcCtx.OauthRpc.Oauth(l.ctx, &oauth.OauthReq{
		Username: req.Username,
	})
	if err != nil {
		return nil, err
	}
	if authResp.AccessToken == "" {
		return nil, errorx.NewCodeError(500, "登录失败,用户名或密码错误")
	}
	logx.Debug(authResp)
	resp = &types.LoginResponse{
		Token: authResp.AccessToken,
	}
	return
}
